import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import re
import math

# 背景地图信息
map_info = {
    "grid_origin_x": -8.25,
    "grid_origin_y": -36.05,
    "grid_resolution": 0.05,
}

grid_origin_x = map_info['grid_origin_x']
grid_origin_y =  map_info['grid_origin_y']
grid_resolution = map_info['grid_resolution']

# 从文件中读取数据
min_rssi = 9999
max_rssi = -9999
data = []
with open('log.txt', 'r') as file:
    for line in file:
        number_regex = r"-?\d+(?:\.\d+)?"
        number_matches = re.findall(number_regex, line)
        if len(number_matches) == 3:
            data.append((float(number_matches[0]), float(number_matches[1]), float(number_matches[2])))
            min_rssi = min(min_rssi,  float(number_matches[2]))
            max_rssi = max(max_rssi,  float(number_matches[2]))
        elif len(number_matches) == 2:
            data.append((float(number_matches[0]), float(number_matches[1]), float("nan")))

# 加载并显示背景图片
bg_map = mpimg.imread('map.png')

# 计算网格大小
grid_size_x = bg_map.shape[1]
grid_size_y = bg_map.shape[0]

# 创建网格
grid = np.zeros((grid_size_y, grid_size_x))

# 创建画布和子图
fig, ax = plt.subplots()
# 在第一个子图中显示背景图
ax.imshow(bg_map, cmap='gray')

# 图例
disconnect = {'x': [], 'y': []}
more60 = {'x': [], 'y': []}
more70 = {'x': [], 'y': []}
more80 = {'x': [], 'y': []}
less80 = {'x': [], 'y': []}

# 填充热力图
for x, y, temp in data:
    
    grid_index_x = int((x - grid_origin_x) / grid_resolution)
    grid_index_y = grid_size_y - int((y - grid_origin_y) / grid_resolution)
    if math.isnan(temp):
        disconnect['x'].append(grid_index_x)
        disconnect['y'].append(grid_index_y)
    elif temp > -60:
        more60['x'].append(grid_index_x)
        more60['y'].append(grid_index_y)
    elif temp > -70:
        more70['x'].append(grid_index_x)
        more70['y'].append(grid_index_y)
    elif temp > -80:
        more80['x'].append(grid_index_x)
        more80['y'].append(grid_index_y)
    else:
        less80['x'].append(grid_index_x)
        less80['y'].append(grid_index_y)

ax.plot(more60['x'], more60['y'], 'gx', markersize=10, label="> -60")
ax.plot(more70['x'], more70['y'], "bx", markersize=10, label="> -75")
ax.plot(more80['x'], more80['y'], "yx", markersize=10, label="> -80")
ax.plot(less80['x'], less80['y'], "rx", markersize=10, label="<= -80")
ax.plot(disconnect['x'], disconnect['y'] ,"kx", markersize=10, label="disconected")

plt.legend()
plt.show()